package com.boarsoft.boar.gateway.web.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.eclipse.jetty.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.auth.TokenAuth;
import com.boarsoft.boar.gateway.GatewayConfig;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.config.core.Configable;
import com.boarsoft.webapp.HttpServiceHandler;

/**
 * 根据HTTP请求参数中的_target值，将请求转发给对应的服务器
 * 
 * @author Mac_J
 *
 */
public class PrometheusProxyImpl implements HttpServiceHandler, Configable {
	private static final Logger log = LoggerFactory.getLogger(PrometheusProxyImpl.class);

	@Autowired
	protected TokenAuth tokenAuth;

	protected String apiKey = "key";
	protected String targetKey = "target";
	protected String path = "/prometheus";

	@Override
	public void config() {
		GatewayConfig.config();
	}

	@Override
	public boolean process(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
		log.info(JsonUtil.toJSONString(req.getHeaderNames()));
		String key = req.getHeader(apiKey);
		if (Util.strIsEmpty(key)) {
			rsp.sendError(HttpStatus.BAD_REQUEST_400);
			return true;
		}
		String target = req.getHeader(targetKey);
		if (Util.strIsEmpty(target)) {
			rsp.sendError(HttpStatus.BAD_REQUEST_400);
			return true;
		}
		//allowed target array
		String[] ata = GatewayConfig.getProperty(key, "").split(",");
		// 获取这个API Key是否访问指定的Prometheus服务器实例
		log.info(req.getPathInfo());
		if (ArrayUtils.indexOf(ata, target) < 0) {
			rsp.sendError(HttpStatus.FORBIDDEN_403);
			return true;
		}
		String addr = GatewayConfig.getProperty(target, null);
		if (Util.strIsEmpty(addr)) {
			rsp.sendError(HttpStatus.NOT_FOUND_404);
			return true;
		}
		// 检查token
		String token = req.getHeader("Authorization");
		if (Util.strIsEmpty(token)) {
			rsp.sendError(HttpStatus.UNAUTHORIZED_401);
			return true;
		}
		log.info("Authorization={}", token);
		try {
			token = StringUtils.replace(token, "Bearer ", "");
			ReplyInfo<Object> ro = tokenAuth.check(token);
			if (!ro.isSuccess()) {
				rsp.sendError(HttpStatus.FORBIDDEN_403);
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		StringBuffer sb = req.getRequestURL();
		log.info(sb.toString());
		// 替换原请求中的域名为实际提供服务的应用地址
		// http://xxx/.... 替换xxx部份
		int i = sb.substring(7).indexOf("/") + 7;
		sb.replace(7, i, addr);
		String qs = req.getQueryString();
		if (!StringUtils.isEmpty(qs)) {
			sb.append("?").append(qs);
		}
		String url = StringUtils.replace(sb.toString(), path, "");
		log.info("rewrite {} to {}", req.getRequestURI(), url);
		req.setAttribute("rewriteUrl", url);
		return false;
	}

	public String getApiKey() {
		return apiKey;
	}

	public void setApiKey(String apiKey) {
		this.apiKey = apiKey;
	}

	public TokenAuth getTokenAuth() {
		return tokenAuth;
	}

	public void setTokenAuth(TokenAuth tokenAuth) {
		this.tokenAuth = tokenAuth;
	}

	public String getTargetKey() {
		return targetKey;
	}

	public void setTargetKey(String targetKey) {
		this.targetKey = targetKey;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
}